package com.rc.activity;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Locale;

import android.app.DatePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.rc.activity.dao.tbl_Merchant;
import com.rc.activity.dao.tbl_Receipt;
import com.rc.activity.dao.tbl_ReceiptDao;
import com.rc.activity.dao.tbl_Settings;
import com.rc.activity.provider.Contract;
import com.rc.adapter.MerChantNameAdapter;
import com.rc.db.DatabaseSupport;
import com.rc.object.MerchantObj;
import com.rc.util.Util;
import com.telpoo.frame.ui.BaseActivity;

public class ReceiptMerchantInfo extends BaseActivity implements
		OnClickListener, TextWatcher {

	private LinearLayout llSave, llCancel, llListViewMerchant;
	private TextView txtMerchantName, txtZipCode, txtState, txtCity,
			txtAddress, txtTelephone, txtPurchaseDate, txtCountry;
	private ImageView imgViewLogo;
	private ListView lvMerChantName;

	private MerChantNameAdapter adpDialog = null;
	private boolean isCreate;
	private long mMerchantID;
	private ArrayList<tbl_Merchant> arrMerchantSearch;
	private boolean isShowList = true;
	private ArrayList<tbl_Merchant> arrMerchant;
	private tbl_Merchant objMerchant;
	private tbl_Receipt obj_Receipt;

	public static void callIntentNew(Context ct, boolean isCreate) {
		Intent it = new Intent(ct, ReceiptMerchantInfo.class);
		it.putExtra("isCreate", isCreate);
		ct.startActivity(it);
	}

	public static void callIntentEdit(Context ct, long mMerchantID) {
		Intent it = new Intent(ct, ReceiptMerchantInfo.class);
		it.putExtra("MERCHANT_ID", mMerchantID);
		ct.startActivity(it);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.receipt_merchant_info);

		llSave = (LinearLayout) findViewById(R.id.llSave);
		llCancel = (LinearLayout) findViewById(R.id.llCancel);
		imgViewLogo = (ImageView) findViewById(R.id.imgViewLogo);
		llListViewMerchant = (LinearLayout) findViewById(R.id.llListViewMerchant);
		txtMerchantName = (TextView) findViewById(R.id.txtMerchantName);
		txtCountry = (TextView) findViewById(R.id.txtCountry);
		txtPurchaseDate = (TextView) findViewById(R.id.txtPurchaseDate);
		txtZipCode = (TextView) findViewById(R.id.txtZipCode);
		txtState = (TextView) findViewById(R.id.txtState);
		txtCity = (TextView) findViewById(R.id.txtCity);
		txtAddress = (TextView) findViewById(R.id.txtAddress);
		txtTelephone = (TextView) findViewById(R.id.txtTelephone);
		lvMerChantName = (ListView) findViewById(R.id.lvMerChantName);

		llSave.setOnClickListener(this);
		llCancel.setOnClickListener(this);
		// imgViewLogo.setOnClickListener(this);
		txtPurchaseDate.setOnClickListener(this);
		txtMerchantName.addTextChangedListener(this);

	}

	@Override
	protected void onResume() {
		super.onResume();

		if (getIntent().hasExtra("isCreate")) {
			((TextView) findViewById(R.id.txtCenterTitle))
					.setText(getString(R.string.new_receipt));
			imgViewLogo.setVisibility(View.GONE);
			isCreate = getIntent().getBooleanExtra("isCreate", true);
		}
		// get all merchant on sqlite
		getAllMerchant();

		// nếu iscreate = false ,The form is update 
		if (!isCreate) {
			addDataUI();
		} else {
			txtPurchaseDate.setText(Util.getDefaultInfor());
		}

	}

	/**
	 * get tbl_Merchant in SQLite by ID Merchant
	 */
	private void addDataUI() {
		if (getIntent() != null) {
			mMerchantID = getIntent().getLongExtra("MERCHANT_ID", 0);
			if (mMerchantID == 0) {
				return;
			}

			tbl_Merchant objMerchant = new MerchantObj();
			objMerchant = DatabaseSupport.getMerchantByID(mMerchantID,
					ReceiptMerchantInfo.this);
			if (objMerchant == null) {
				return;
			}
			new DownloadImageTask(imgViewLogo).execute(objMerchant.getLogo());
			txtMerchantName.setText(objMerchant.getName());
			txtAddress.setText(objMerchant.getAddress());
			txtCity.setText(objMerchant.getCity());
			txtState.setText(objMerchant.getState());
			txtTelephone.setText(objMerchant.getPhoneNumber());
			txtZipCode.setText(objMerchant.getZipCode());
			obj_Receipt = new tbl_Receipt();
			obj_Receipt = DatabaseSupport.getReceiptByMerchantID(mMerchantID,
					ReceiptMerchantInfo.this);
			txtPurchaseDate.setText(obj_Receipt.getPurchaseTime());
			txtCountry.setText(obj_Receipt.getMerchantCountry());
			if (!DatabaseSupport.ruleRecipt(obj_Receipt.getReceiptID(), this)) {
				txtMerchantName.setEnabled(false);
				txtAddress.setEnabled(false);
				txtCity.setEnabled(false);
				txtState.setEnabled(false);
				txtTelephone.setEnabled(false);
				txtZipCode.setEnabled(false);
				txtPurchaseDate.setEnabled(false);
				txtCountry.setEnabled(false);
				llSave.setVisibility(View.GONE);
			}
		}
	}

	private tbl_Merchant getMerchantUI() {
		tbl_Merchant objMerchant = new tbl_Merchant();

		String merchantName = txtMerchantName.getText().toString();
		String address = txtAddress.getText().toString();

		if (!isCreate) {
			objMerchant = DatabaseSupport.getMerchantByID(mMerchantID,
					ReceiptMerchantInfo.this);
			objMerchant.setIsUpdate("1");
		} else {
			objMerchant.setIsCreate("1");
		}
		objMerchant.setMerchantID(Long.valueOf(Util.getCurrentTime()));
		objMerchant.setAddress(address);
		objMerchant.setCity(txtCity.getText().toString());
		objMerchant.setName(merchantName);
		objMerchant.setPhoneNumber(txtTelephone.getText().toString());
		objMerchant.setState(txtState.getText().toString());

		objMerchant.setZipCode(txtZipCode.getText().toString());
		return objMerchant;
	}

	/**
	 * get all merchant in sqlite
	 */

	private void getAllMerchant() {
		Cursor cursor = this.getContentResolver().query(
				Contract.CONTENT_URI_MERCHANT, null, null, null, null);
		arrMerchant = new ArrayList<tbl_Merchant>();
		arrMerchant = MerchantObj.getObjectbyCursor(cursor);
		getDefaultInforTime();
		adpDialog = new MerChantNameAdapter(ReceiptMerchantInfo.this,
				arrMerchant, "");
		lvMerChantName.setAdapter(adpDialog);
		lvMerChantName.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

			}
		});
	}

	private boolean validateMerchant() {
		if (!Util.validateText(txtMerchantName)) {
			Util.setError((EditText) txtMerchantName,
					getString(R.string.please_enter_report_name));
		} else {
			return true;
		}
		return false;
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.llSave:
			if (validateMerchant()) {
				if (!isCreate) {
					long idMerchant = 0;
					tbl_Merchant objMerchant = new tbl_Merchant();
					objMerchant.setAddress(txtAddress.getText().toString());
					objMerchant.setName(txtMerchantName.getText().toString());
					objMerchant.setPhoneNumber(txtTelephone.getText()
							.toString());
					objMerchant.setCity(txtCity.getText().toString());
					objMerchant.setState(txtState.getText().toString());
					objMerchant.setZipCode(txtZipCode.getText().toString());

					// insert or update merchant
					idMerchant = DatabaseSupport.insertOrUpdateMerchant(
							objMerchant, ReceiptMerchantInfo.this);

					// get data receipt
					obj_Receipt.setMerchantID(idMerchant);
					obj_Receipt.setPurchaseTime(txtPurchaseDate.getText()
							.toString());
					obj_Receipt.setIsUpdate("1");

					// update receipt
					if (this.getContentResolver().update(
							Contract.CONTENT_URI_RECEIPT,
							obj_Receipt.getContentValues(),
							tbl_ReceiptDao.Properties.ReceiptID.columnName
									+ " = " + obj_Receipt.getReceiptID(), null) > 0) {
						finish();
					}

				} else {
					objMerchant = new tbl_Merchant();
					objMerchant = getMerchantUI();
					objMerchant.setIsCreate("1");
					Uri uri = this.getContentResolver().insert(
							Contract.CONTENT_URI_MERCHANT,
							objMerchant.getContentValues());
					if (uri != null) {
						obj_Receipt = new tbl_Receipt();
						obj_Receipt.setReceiptID(Long.valueOf(Util
								.getCurrentTime()));
						obj_Receipt.setMerchantID(Long.valueOf(uri
								.getLastPathSegment()));

						// get home currency
						Cursor cursor = this.getContentResolver().query(
								Contract.CONTENT_URI_SETTING, null, null, null,
								null);
						tbl_Settings objSetting = new tbl_Settings();
						objSetting = tbl_Settings.getObjectByCursor(cursor);

						// set currencyCode
						obj_Receipt.setCurrencyCode(objSetting
								.getCurrencyCode());
						obj_Receipt.setPurchaseTime(txtPurchaseDate.getText()
								.toString());
						obj_Receipt.setIsCreate("1");
						obj_Receipt.setReceiptType("4");
						obj_Receipt.setIsDelete("");
						obj_Receipt.setTotal("0.00");
						obj_Receipt.setReceiptImage("");
						obj_Receipt.setIsUpdate("");
						obj_Receipt.setTax("0.00");
						obj_Receipt.setCreatedTime(System.currentTimeMillis()
								/ 1000 + "");
						obj_Receipt.setDiscount("0.00");
						obj_Receipt.setSubtotal("0.00");
						obj_Receipt.setUserID(DatabaseSupport.getTbl_User(
								ReceiptMerchantInfo.this).getUserID());
						obj_Receipt.setTotal("0.00");
						uri = this.getContentResolver().insert(
								Contract.CONTENT_URI_RECEIPT,
								obj_Receipt.getContentValues());
						if (uri != null) {
							ReceiptBoxDetailAddItem.callItent(this,
									Long.valueOf(uri.getLastPathSegment()),
									true);
						}
					}

				}
			}

			break;
		case R.id.llCancel:
			finish();
			break;
		// case R.id.imgViewLogo:
		// createDialogEditPhoto();
		// break;
		case R.id.txtPurchaseDate:
			showDatePickerDialog();
			break;
		default:
			break;
		}
	}

	private Calendar cal;

	private void getDefaultInforTime() {
		cal = Calendar.getInstance();
		SimpleDateFormat dft = null;
		dft = new SimpleDateFormat("dd-MM-yyyy", Locale.getDefault());
		String strDate = dft.format(cal.getTime());
	}

	public ArrayList<tbl_Merchant> searchListView(
			ArrayList<tbl_Merchant> mListView, String contentSearch) {
		ArrayList<tbl_Merchant> arrMerchant = new ArrayList<tbl_Merchant>();
		for (int i = 0; i < mListView.size(); i++) {
			if (mListView.get(i).getName().toUpperCase()
					.contains(contentSearch.toUpperCase())) {
				arrMerchant.add(mListView.get(i));
			}

		}
		return arrMerchant;
	}

	/**
	 * TODO : edit photo merchant
	 */
	/*
	 * private void createDialogEditPhoto() { dialog = new Dialog(this);
	 * dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
	 * dialog.setContentView(R.layout.dialog_receipt_merchant_picture);
	 * 
	 * LinearLayout llViewAnblum, llViewImage; llViewAnblum = (LinearLayout)
	 * dialog.findViewById(R.id.llViewAnblum); llViewImage = (LinearLayout)
	 * dialog.findViewById(R.id.llViewImage);
	 * llViewAnblum.setOnClickListener(new View.OnClickListener() {
	 * 
	 * @Override public void onClick(View v) { // TODO Auto-generated method
	 * stub Intent intent = new Intent(); intent.setType("image/*");
	 * intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(
	 * Intent.createChooser(intent, "Select Picture"), Const.GALLERY_REQUEST); }
	 * }); llViewImage.setOnClickListener(new View.OnClickListener() {
	 * 
	 * @Override public void onClick(View v) { // TODO Auto-generated method
	 * stub ImageViewScreen .callIntentBitMap(ReceiptMerchantInfo.this, null); }
	 * }); dialog.show();
	 * 
	 * }
	 */

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (getIntent().hasExtra("IS_TRUE")) {

		}

	}

	@Override
	public void beforeTextChanged(CharSequence s, int start, int count,
			int after) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		if (txtMerchantName.getText().toString().length() > 1 && !isShowList) {
			arrMerchantSearch = new ArrayList<tbl_Merchant>();
			arrMerchantSearch = searchListView(arrMerchant, txtMerchantName
					.getText().toString());
			adpDialog.notiB(arrMerchantSearch);
			Util.setListViewHeightBasedOnChildren(lvMerChantName);
			if (arrMerchantSearch.size() > 0) {
				llListViewMerchant.setVisibility(View.VISIBLE);
			} else {
				llListViewMerchant.setVisibility(View.GONE);
			}

			lvMerChantName.setOnItemClickListener(new OnItemClickListener() {

				@Override
				public void onItemClick(AdapterView<?> parent, View view,
						int position, long id) {
					tbl_Merchant objMerchant = new tbl_Merchant();
					objMerchant = arrMerchantSearch.get(position);
					txtMerchantName.setText(objMerchant.getName().toString());
					txtAddress.setText(objMerchant.getAddress().toString());
					llListViewMerchant.setVisibility(View.GONE);
				}
			});
		} else {
			llListViewMerchant.setVisibility(View.GONE);
			isShowList = false;
		}
	}

	@Override
	public void afterTextChanged(Editable s) {
		// TODO Auto-generated method stub

	}

	private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
		ImageView bmImage;

		public DownloadImageTask(ImageView bmImage) {
			this.bmImage = bmImage;
		}

		protected Bitmap doInBackground(String... urls) {
			String urldisplay = urls[0];
			Bitmap mIcon11 = null;
			try {
				InputStream in = new java.net.URL(urldisplay).openStream();
				mIcon11 = BitmapFactory.decodeStream(in);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return mIcon11;
		}

		protected void onPostExecute(Bitmap result) {
			if (result != null) {
				imgViewLogo.setBackgroundResource(R.drawable.border_image);
			}
			bmImage.setImageBitmap(result);
		}
	}

	public void showDatePickerDialog() {
		int date = 0, month = 0, year = 0;

		OnDateSetListener callback = new OnDateSetListener() {
			public void onDateSet(DatePicker view, int year, int monthOfYear,
					int dayOfMonth) {
				// Date
				try {
					txtPurchaseDate.setText(Util.validateDateMonth(dayOfMonth)
							+ "-" + Util.validateDateMonth(monthOfYear + 1)
							+ "-" + year);

				} catch (Exception e) {
					// TODO: handle exception
					e.printStackTrace();
				}
			}
		};
		String s = txtPurchaseDate.getText() + "";
		if (getString(R.string.dateofbirth).equals(s)) {
			Calendar cal = Calendar.getInstance();
			date = cal.getTime().getDate();
			month = cal.getTime().getMonth();
			year = cal.get(Calendar.YEAR);
		} else {
			String strArrtmp[] = s.split("-");
			date = Integer.parseInt(strArrtmp[0]);
			month = Integer.parseInt(strArrtmp[1]) - 1;
			year = Integer.parseInt(strArrtmp[2]);
		}
		DatePickerDialog pic = new DatePickerDialog(ReceiptMerchantInfo.this,
				callback, year, month, date);
		pic.setTitle(getString(R.string.choose_calendar));
		pic.show();
	}

}
